package org.oy.sealogger.ui;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;

import java.util.Observable;
import java.util.Observer;


import org.oy.sealogger.parser.RMCSentence;
import org.oy.sealogger.parser.CurrentState;

public class Location implements Observer {

	
	private String longitude = "";
	private String latitude = "";
	
	private Image location;
	private ImageLoader imageLoader = new ImageLoader();
	private LoggerGraphics lg = null;
	
	private int x;
	private int y;
	private int width;
	private int height;
	
	public Location(LoggerGraphics l) {
		this.lg = l;
		location = imageLoader.getImage("LOCATION.png");	
	}
	
	public void draw(Graphics g, int x, int y, int w, int h) {
		Graphics2D g2 = (Graphics2D)g;
		
		this.setVariables(x,y,w,h);		
		g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
		
		//FIXME
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		g2.drawImage(location, x, y, w, h, this.imageLoader);
		
		this.drawLocationString(g2,x,y,w,h);
	}
	
	
	
	public void drawLocationString(Graphics2D g2, int x, int y, int w, int h) {		
		int fontSize = (int)(Math.round(0.10 * w));
    	int yCenter = (int)(Math.round(0.10 * h));
    	int yLat = y + (h / 2) + yCenter;
    	int yLon = y + (h / 2) + fontSize + yCenter;
    	//int yLat = y + (h / 2) - yCenter;
    	//int yLon = y + (h / 2) + yCenter;
    	//double speedDouble = Double.valueOf();
    	int xLat = x + (int)(Math.round(0.14 * w));
    	int xLon = x + (int)(Math.round(0.14 * w));
		
		
		g2.setPaint(Color.BLACK);
	    g2.setFont(new Font("Arial", Font.BOLD, fontSize));
	    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
	    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		g2.drawString(this.latitude, xLat, yLat);
		g2.drawString(this.longitude, xLon, yLon);
	}
	
	private void setVariables(int x, int y, int w, int h) {
		this.x = x;
		this.y = y;
		this.width = w;
		this.height = h;
	}

	public void update(Observable state, Object arg) {
		RMCSentence rmc = ((CurrentState)state).getGPSLocation();

		String lon = rmc.getLongitude();
		String lat = rmc.getLatitude();
		this.setLocation(lon, lat);
		
		this.lg.repaint(this.x,this.y,this.x + this.width,this.y + this.height);
	}	

	public void setLocation(String lon, String lat) {
		this.latitude = lat;
		this.longitude = lon;
	}
	

}
